-- 采矿
-- 白色矿石 铋矿
-- 绿色矿石 亚基矿
-- 绿色矿石 镔爪矿
-- 蓝色矿石 虚无石

-- 采药
-- 白色草药-菌丝花
-- 绿色草药-圣祝棠
-- 绿色草药-阿拉索之矛
-- 绿色草药-惑露堇
-- 绿色草药-球首兰
-- 蓝色草药-虚无之莲
local targets = {
  {itemID = 210805, tartgetPrice = 10*10000, name = "圣祝棠"},
  -- {itemID = 210796, tartgetPrice = 15*10000, name = "菌丝花"},
  -- {itemID = 210809, tartgetPrice = 30*10000, name = "阿拉索之矛"},
  -- {itemID = 210799, tartgetPrice = 25*10000, name = "惑露堇"},
  -- {itemID = 210802, tartgetPrice = 14*10000, name = "球首兰"},
  -- {itemID = 213197, tartgetPrice = 300*10000, name = "虚无之莲"},
  -- {itemID = 2324, tartgetPrice = 0.01*10000, name = "漂白液"},
}

local filterTargets = {}
-- api地址
-- https://warcraft.wiki.gg/wiki/World_of_Warcraft_API
local searchIdx = 1
-- local COMMODITY_SEARCH_RESULTS_UPDATED_Count = 0
local buyingItem = nil
local buyingTimer = nil
local searchCompleted = false
-- 发送物品
function Get_INGENUITY()
  local itemIDs = {210796, 210802}
  for i = 1, #itemIDs do
    local itemSlot = GetItemSlot(itemIDs[i])
    if itemSlot then
      print("itemSlot", itemSlot.bagID, itemSlot.slotID)
      C_Container.PickupContainerItem(itemSlot.bagID, itemSlot.slotID)
      ClickSendMailItemButton(i)
    end
  end
  SendMail("强丶壮", "Hey Bob", "Hows it going, Bob?")
  print("SendMail---")
end


-- 测试客人订单
function Get_INGENUITY4()
  local customerOrders = C_CraftingOrders.GetCustomerOrders()
  print(TableToString(customerOrders))
end

-- 锻造 镔爪合金
function Get_INGENUITY3()
  -- local skillLineID = C_TradeSkillUI.GetProfessionChildSkillLineID()
  -- print("锻造skillLineID:", skillLineID)
  local skillLineID = 2872
  print("锻造skillLineID:", skillLineID)
  local currencyType = C_TradeSkillUI.GetConcentrationCurrencyID(skillLineID)
  local currencyInfo = C_CurrencyInfo.GetCurrencyInfo(currencyType)
  print("货币名称:", currencyInfo.name, currencyInfo.quantity)
  local recipeID = 450219
  local craftingReagents = {
    {dataSlotIndex = 1, itemID = 222418, quantity = 2}, -- 2星心核合金
    {dataSlotIndex = 2, itemID = 210937, quantity = 5}, -- 2星镔爪框
  }
  local operationInfo = C_TradeSkillUI.GetCraftingOperationInfo(recipeID, craftingReagents, "1234", false)
  print("operationInfo-----------", operationInfo)
  if operationInfo and operationInfo.concentrationCost < currencyInfo.quantity then
    -- C_TradeSkillUI.CraftRecipe(recipeSpellID [, numCasts [, craftingReagents [, recipeLevel [, orderID [, applyConcentration]]]]])
    C_TradeSkillUI.CraftRecipe(recipeID, 1, craftingReagents, nil, nil, true)
    print("能使用专注制作")
  else
    print("不能使用专注制作")
  end
  print(TableToString(operationInfo))
end

-- 附魔 晶脉辉煌
function Get_INGENUITY2(args)
  print("5555")
  local recipeID = 445333
  local recipeInfo = C_TradeSkillUI.GetRecipeInfo(recipeID)
  local professionInfo = C_TradeSkillUI.GetProfessionInfoByRecipeID(recipeID)
  local craftingReagents = {
    -- {dataSlotIndex = 0, itemID = 213610, quantity = 20}, -- 晶脉粉末
    {dataSlotIndex = 1, itemID = 219946, quantity = 69}, -- 1星风暴之尘
    {dataSlotIndex = 1, itemID = 219947, quantity = 6}, -- 2星风暴之尘
    {dataSlotIndex = 2, itemID = 219949, quantity = 10}, -- 1星粼光碎片
    {dataSlotIndex = 3, itemID = 219952, quantity = 1}, -- 1星耀辉水晶
  }
  local operationInfo = C_TradeSkillUI.GetCraftingOperationInfo(recipeID, craftingReagents, "1234", true)
  print("recipeInfo-----------")
  TraverseTable(recipeInfo)
  print("professionInfo-----------")
  TraverseTable(professionInfo)
  print("operationInfo-----------")
  TraverseTable(operationInfo)
  print(TableToString(operationInfo))
  -- 获取附魔羊皮纸位置
  -- local targetLocation = GetItemLocation(38682)
  -- -- 浮光精通 recipeID 445381
  -- C_TradeSkillUI.CraftEnchant(445381, 1, {}, targetLocation)
end

hooksecurefunc(C_TradeSkillUI, "CraftEnchant",
		function(recipeID, amount, craftingReagentInfoTbl, enchantItemLocation, concentrating)
      print("CraftEnchant---recipeID", recipeID)
      print("CraftEnchant---amount", amount)
      print("CraftEnchant---concentrating", concentrating)
      print("###", #craftingReagentInfoTbl)
      TraverseTable(craftingReagentInfoTbl)
      print(TableToString(craftingReagentInfoTbl))
			-- OnCraft(CraftSim.OnCraftData {
			-- 	recipeID = recipeID,
			-- 	amount = amount or 1,
			-- 	craftingReagentInfoTbl = craftingReagentInfoTbl or {},
			-- 	itemTargetLocation = enchantItemLocation,
			-- 	isEnchant = true,
			-- 	concentrating = concentrating,
			-- 	callerData = {
			-- 		api = "CraftEnchant",
			-- 		params = { recipeID, amount, craftingReagentInfoTbl, enchantItemLocation, concentrating },
			-- 	}
			-- })
		end
)

hooksecurefunc(C_TradeSkillUI, "CraftRecipe",
  function(recipeID, amount, craftingReagentInfoTbl, recipeLevel, orderID, concentrating)
    print("CraftRecipe---recipeID", recipeID)
      print("CraftRecipe---amount", amount)
      print("CraftRecipe---recipeLevel", recipeLevel)
      print("CraftRecipe---concentrating", concentrating)
      print("###", #craftingReagentInfoTbl)
      TraverseTable(craftingReagentInfoTbl)
      print(TableToString(craftingReagentInfoTbl))
  end
)

function TableToString(tbl)
  local result = "{"
  
  for key, value in pairs(tbl) do
      result = result .. "[" .. tostring(key) .. "] = "
      
      if type(value) == "table" then
          result = result .. TableToString(value)  -- 递归调用
      else
          result = result .. tostring(value)
      end
      
      result = result .. ", "
  end
  
  -- 去掉最后的逗号和空格
  result = result:sub(1, -3) .. "}"
  
  return result
end

function TraverseTable(tbl)
    for key, value in pairs(tbl) do
        if type(value) == "table" then
            print(key .. " 是一个表，递归遍历")
            TraverseTable(value)  -- 递归遍历
        else
            print(key, value)
        end
    end
end

function Get_INGENUITY1()
  print("6666")
  -- 获取当前专业剩余专注
  local skillLineID = C_TradeSkillUI.GetProfessionChildSkillLineID()
  print("skillLineID:", skillLineID)
  local currencyType = C_TradeSkillUI.GetConcentrationCurrencyID(skillLineID)
  local currencyInfo = C_CurrencyInfo.GetCurrencyInfo(currencyType)

  print("货币名称:", currencyInfo.name)
  print("剩余专注:", currencyInfo.quantity)

  local info = C_TradeSkillUI.GetProfessionInfoBySkillLineID(skillLineID)

  

  print("professionName:", info.professionName)
  print("sourceCounter:", info.sourceCounter)
  print("professionID:", info.professionID)
  print("expansionName:", info.expansionName)
  print("skillLevel:", info.skillLevel)
  print("maxSkillLevel:", info.maxSkillLevel)
  print("skillModifier:", info.skillModifier)
  -- 晶脉辉煌 recipeID 445333
  local recipeID = 445333
  local recipeInfo = C_TradeSkillUI.GetRecipeInfo(recipeID)
  print("晶脉辉煌", recipeInfo.name)
  -- /dump C_Item.GetItemInfo(38682)
  -- 获取附魔
  local targetLocation = GetItemLocation(38682)
  -- 浮光精通 recipeID 445381
  C_TradeSkillUI.CraftEnchant(445381, 1, {}, targetLocation)
  -- for _, id in pairs(C_TradeSkillUI.GetAllRecipeIDs()) do
  --   local recipeInfo = C_TradeSkillUI.GetRecipeInfo(id)
  --   -- print(recipeInfo.recipeID, recipeInfo.name)
  --   if(recipeInfo.name == "浮光精通") then
  --     print("浮光精通", recipeInfo.recipeID)
  --   end
  -- end
end

function GetItemSlot(targetItemID)
  local slotTable = nil
-- 遍历所有背包槽（包括背包、银行等）
  for bagID = 0, NUM_BAG_SLOTS do
    -- 获取当前背包的槽位数
    local numSlots = C_Container.GetContainerNumSlots(bagID)
    -- 遍历当前背包的所有槽位
    for slotID = 1, numSlots do
        -- 获取当前槽位的物品 ID
        local itemID = C_Container.GetContainerItemID(bagID, slotID)
        -- print("itemID:", itemID, "targetItemID:", targetItemID)
        if itemID == targetItemID then
          slotTable = {bagID = bagID, slotID = slotID, itemLocation = ItemLocation:CreateFromBagAndSlot(bagID, slotID)}
          -- 输出物品的位置信息
          -- print(string.format("物品 %d 在背包 %d 的槽位 %d，位置: %s", targetItemID, bagID, slotID, itemLocation:GetDebugString()))
          
          -- 如果找到了目标物品，你可以在这里进行其他操作
          -- 例如，做一些物品检查或移动操作
      end
    end
  end
  return slotTable
end

function GetItemLocation(targetItemID)
  local itemLocation = nil
  print("GetItemLocation:", targetItemID)
  -- 你需要查找的物品的 ID（替换为目标物品的 ID）
  -- local targetItemID = 12345  -- 假设你要查找的物品 ID 是 12345

  -- 遍历所有背包槽（包括背包、银行等）
  for bagID = 0, NUM_BAG_SLOTS do
      -- 获取当前背包的槽位数
      local numSlots = C_Container.GetContainerNumSlots(bagID)
      -- 遍历当前背包的所有槽位
      for slotID = 1, numSlots do
          -- 获取当前槽位的物品 ID
          local itemID = C_Container.GetContainerItemID(bagID, slotID)
          -- print("itemID:", itemID, "targetItemID:", targetItemID)
          if itemID == targetItemID then
            print("54432312312----------")
            -- 获取物品的 ItemLocationMixin
            itemLocation = ItemLocation:CreateFromBagAndSlot(bagID, slotID)
            
            -- 输出物品的位置信息
            -- print(string.format("物品 %d 在背包 %d 的槽位 %d，位置: %s", targetItemID, bagID, slotID, itemLocation:GetDebugString()))
            
            -- 如果找到了目标物品，你可以在这里进行其他操作
            -- 例如，做一些物品检查或移动操作
        end
      end
  end
  return itemLocation
end

-- /run CheckMXT_Quest()
function CheckMXT_Quest()
  local questIDs = {29510, 29508} -- 替换为你的任务ID列表
  for _, questID in ipairs(questIDs) do
    local isCompleted = C_QuestLog.IsQuestFlaggedCompleted(questID)
    local questName = questID == 29510 and "附魔马戏团专业任务" or "锻造马戏团专业任务"
    if isCompleted then
        print("任务 \"" .. (questName) .. "\" 已完成！")
    else
        print("任务 \"" .. (questName) .. "\" 未完成！")
    end
  end
end

--/run BestBeatBoom_fireStartBuyItem(210805, 1)
function BestBeatBoom_fireScanItem()
  -- local myTimer = C_Timer.NewTimer(3, function() print("Hello") end)
  -- print(myTimer:IsCancelled()) -- false
  -- myTimer:Cancel()
  -- print(myTimer:IsCancelled()) -- true
  C_Timer.NewTicker(0.8, function()
    BestBeatBoom_fireScanItem1()
  end)
end

function BestBeatBoom_fireScanItem1()
  print('BestBeatBoom_fireScanItem')
  searchCompleted = false
  local itemKey = C_AuctionHouse.MakeItemKey(targets[searchIdx].itemID)
  C_AuctionHouse.SendSearchQuery(itemKey, {}, false)
  searchIdx = searchIdx + 1
  if searchIdx > #targets then
    searchIdx = 1
  end
end

-- /run getTargetInfo(210809)
-- /run getTargetInfo(210802)
function GetTargetById(itemID)
  local item = nil
  for k, v in pairs(targets) do
    if v.itemID == itemID then
      item = v
    end
  end
  return item
end

-- /run BestBeatBoom_fireStartBuyItem()
function BestBeatBoom_fireStartBuyItem()
  print('BestBeatBoom_fireStartBuyItem', buyingItem, #filterTargets)
  if buyingItem == nil and #filterTargets > 0 then
    buyingItem = filterTargets[1]
    -- print(3, buyingItem)
    -- for k, v in pairs(buyingItem) do
    --   print(k, v)
    -- end
    print(string.format("buying item name:%s, 价格:%d, 目标价:%d, 数量:%d", buyingItem.name, buyingItem.unitPrice, buyingItem.tartgetPrice, buyingItem.quantity))
    C_AuctionHouse.StartCommoditiesPurchase(buyingItem.itemID, buyingItem.quantity)
    -- C_AuctionHouse.StartCommoditiesPurchase(buyingItem.itemID, 1)
    buyingTimer = C_Timer.NewTimer(1, function()
      cancelBuying()
      C_AuctionHouse.CancelCommoditiesPurchase()
    end)
  end
end

function cancelBuying()
  buyingTimer = nil
  buyingItem = nil
  if #filterTargets > 0 then
    table.remove(filterTargets, 1)
  end
  
end

local frame = CreateFrame("Frame")

function frame:COMMODITY_SEARCH_RESULTS_UPDATED(event, itemID)
  if searchCompleted then return end
  -- print('COMMODITY_SEARCH_RESULTS_UPDATED', itemID, C_AuctionHouse.GetNumCommoditySearchResults(itemID))
  local curItem = GetTargetById(itemID)
  if curItem == nil then return end
  local res = C_AuctionHouse.GetCommoditySearchResultInfo(itemID, 1)
  if (res and (res.unitPrice <= curItem.tartgetPrice) and res.quantity > 10) then
    local quantity = res.quantity * 0.5
    -- if quantity > 50 then
    --   quantity = 50
    -- end
    table.insert(filterTargets, {itemID = itemID, name = curItem.name, tartgetPrice = curItem.tartgetPrice, unitPrice = res.unitPrice, quantity = quantity})
    print(string.format("name:%s, 价格:%d, 目标价:%d, 数量:%d", curItem.name, res.unitPrice, curItem.tartgetPrice, quantity))
  else
    filterTargets = {}
  end
  searchCompleted = true
end

function frame:AUCTION_HOUSE_THROTTLED_SYSTEM_READY(event, ...)
  -- print('AUCTION_HOUSE_THROTTLED_SYSTEM_READY', ...)
  
end

function frame:COMMODITY_PRICE_UPDATED(event, unitPrice, totalPrice)
  if buyingItem == nil then return end
  if unitPrice <= buyingItem.tartgetPrice then
    C_AuctionHouse.ConfirmCommoditiesPurchase(buyingItem.itemID, buyingItem.quantity)
    -- C_AuctionHouse.ConfirmCommoditiesPurchase(buyingItem.itemID, 1)
    print(string.format("竞标成功 %s, 价格：%d, 数量：%d", buyingItem.name, unitPrice, buyingItem.quantity))
  else
    print("价格太高 取消了")
    C_AuctionHouse.CancelCommoditiesPurchase()
  end
  if buyingTimer then
    buyingTimer:Cancel()
  end
  cancelBuying()
  
  -- print(string.format('COMMODITY_PRICE_UPDATED unitPrice:%d, totalPrice:%d', unitPrice, totalPrice))
end

function frame:OnEvent(event, ...)
	self[event](self, event, ...)
end

frame:RegisterEvent("COMMODITY_PRICE_UPDATED")
frame:RegisterEvent("AUCTION_HOUSE_THROTTLED_SYSTEM_READY")
frame:RegisterEvent("COMMODITY_SEARCH_RESULTS_UPDATED")
frame:SetScript("OnEvent", frame.OnEvent)